<template>
  <view
    class="content"
    :style="{
      'padding-top': height + 'px',
    }"
  >
    <view
      :style="{
        height: statusBarHeight + 'px',
      }"
    >
    </view>
    <view
      class="head"
      :style="{
        top: statusBarHeight + 'px',
      }"
    >
      <view class="head_left">
        <u-icon
          name="arrow-left"
          color="#444444"
          size="24"
          :bold="true"
          @click="toBack"
        ></u-icon>
      </view>
      <view class="text">支付</view>
    </view>

    <view class="box">
      <view class="box_top">
        <view class="box_top_title">实付金额</view>
        <view class="box_top_price">
          <view class="box_top_price_unit">￥</view>
          <view class="box_top_price_num">{{ price }}</view>
        </view>
      </view>

      <view class="box_content">
        <view class="box_content_title">选择支付方式</view>
        <view v-for="(item, index) in list" :key="index">
          <view
            class="box_content_item"
            @click="change(item)"
            v-if="item.status == 1"
          >
            <view class="box_content_item_left">
              <image
                class="box_content_item_left_img"
                :src="item.file_url"
                mode=""
              ></image>
              <view class="box_content_item_left_title">{{ item.name }}</view>
            </view>

            <view class="box_content_item_right">
              <image
                v-show="!item.clickable"
                src="../../static/images/my/icon_grzy_quanxuan.png"
                mode=""
              ></image>
              <image
                v-show="item.clickable"
                src="../../static/images/my/icon_grzy_xc_xuanzhong.png"
                mode=""
              ></image>
            </view>
          </view>
        </view>
      </view>

      <view class="bottom">
        <view class="bottom_btn" @click="subFn">立即支付</view>
      </view>
    </view>

    <!-- 支付输入密码框 -->
    <u-popup
      :show="showPwd"
      mode="bottom"
      :round="10"
      @close="closePwd"
      @open="openPwd"
      :closeable="true"
      :closeOnClickOverlay="false"
    >
      <view class="niuPop">
        <view class="niuPop_title">输入支付密码</view>
        <!-- 密码 -->
        <u-input
          class="inputPassword"
          type="password"
          placeholder="请输入密码"
          border="none"
          shape="circle"
          color="#888888"
          :fontSize="inputFont"
          v-model="password"
          placeholderStyle="color:#888888"
        ></u-input>

        <view class="confirm_btn" @click="subPay">确认</view>
      </view>
    </u-popup>

    <!-- 牛勒支付密码设置弹窗 -->
    <u-popup
      :show="show"
      mode="bottom"
      :round="10"
      @close="close"
      @open="open"
      :closeable="true"
      :closeOnClickOverlay="false"
    >
      <view class="niuPop">
        <view class="niuPop_title">设置支付密码</view>
        <!-- 手机号 -->
        <u-input
          class="inputPassword"
          :placeholder="email_or_phone == 2?'请输入邮箱':'请输入手机号'"
          border="none"
          shape="circle"
          color="#888888"
          :fontSize="inputFont"
          v-model="mobile"
          placeholderStyle="color:#888888"
        ></u-input>
        <!-- 验证码 -->
        <u-input
          class="inputPassword"
          type="number"
          placeholder="请输入验证码"
          maxlength="6"
          border="none"
          shape="circle"
          color="#888888"
          :fontSize="inputFont"
          v-model="smsCode"
          placeholderStyle="color:#888888"
        >
          <template slot="suffix">
            <u-code
              ref="uCode"
              @change="codeChange"
              seconds="120"
              changeText="Xs"
            ></u-code>
            <view @tap="getCode" class="codeTip">{{ tips }}</view>
          </template></u-input
        >
        <!-- 密码 -->
        <u-input
          class="inputPassword"
          type="password"
          placeholder="请输入密码"
          border="none"
          shape="circle"
          color="#888888"
          :fontSize="inputFont"
          v-model="password"
          placeholderStyle="color:#888888"
        ></u-input>
        <!-- 确认密码 -->
        <u-input
          class="inputPassword"
          type="password"
          placeholder="请再次确认密码"
          border="none"
          shape="circle"
          color="#888888"
          :fontSize="inputFont"
          v-model="password2"
          placeholderStyle="color:#888888"
        ></u-input>

        <view class="confirm_btn" @click="subPwd">确认</view>
      </view>
    </u-popup>

    <floatingBall></floatingBall>
  </view>
</template>
    
<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      height: 0,
      list: [],
      detail: {},
      price: "",
      from: "",
      id: "",
      payId: 0,
      show: false,
      showPwd: false,
      inputFont: "30rpx",
      tips: "",
      mobile: "",
      smsCode: "",
      password: "",
      password2: "",
      alipayOrderStr: "", // 支付宝订单字符串
      pageUrl: "",
      type:0,
      yitianType:"",
      email_or_phone:""
    };
  },
  onLoad(options) {
    this.detail = JSON.parse(options.detail);
    console.log(this.detail,1111111)
    this.order_id = this.detail.order_id; // 订单id
    this.price = options.price;
    this.from = options.from;
    this.id = options.id;
    this.type = options.type;
    this.getPayList();
  },
  created() {
    const statusBarHeight = uni.getSystemInfoSync(); // 获取手机状态栏高度
    this.statusBarHeight = statusBarHeight.statusBarHeight;
    this.$nextTick(() => {
      uni
        .createSelectorQuery()
        .select(".head")
        .boundingClientRect((data) => {
          this.height = data.height;
        })
        .exec();
    });
  },
  methods: {
    // 验证码
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (!this.mobile) {
        if(this.email_or_phone == 2){
          return uni.$u.toast("请输入邮箱");
        } else {
          return uni.$u.toast("请输入手机号");
        }
        
      }
      if (this.$refs.uCode.canGetCode) {
        if(this.email_or_phone == 2){
          this.$http
          .send_email({ email: this.mobile })
          .then((res) => {
            // 模拟向后端请求验证码
            uni.showLoading({
              title: "正在获取验证码",
            });
            setTimeout(() => {
              uni.hideLoading();
              // 这里此提示会被this.start()方法中的提示覆盖
              uni.$u.toast("验证码已发送");
              // 通知验证码组件内部开始倒计时
              this.$refs.uCode.start();
            }, 2000);
          })
          .catch((error) => {
            console.log(error);
            uni.$u.toast(error);
          });
        } else {
          this.$http
          .sendSmsCaptcha({ mobile: this.mobile })
          .then((res) => {
            // 模拟向后端请求验证码
            uni.showLoading({
              title: "正在获取验证码",
            });
            setTimeout(() => {
              uni.hideLoading();
              // 这里此提示会被this.start()方法中的提示覆盖
              uni.$u.toast("验证码已发送");
              // 通知验证码组件内部开始倒计时
              this.$refs.uCode.start();
            }, 2000);
          })
          .catch((error) => {
            console.log(error);
            uni.$u.toast(error);
          });
        }
        
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    // 支付输入密码打开弹框
    openPwd() {},
    // 支付输入密码关闭弹框
    closePwd() {
      this.showPwd = false;
    },
    // 设置密码打开弹框
    open() {},
    // 设置密码关闭弹框
    close() {
      this.show = false;
    },
    toBack() {
      uni.navigateBack({
        delta: 1,
      });
    },
    change(item) {
      this.$forceUpdate();
      for (let i = 0; i < this.list.length; i++) {
        this.list[i].clickable = false;
      }
      item.clickable = true;
      this.payId = item.id;
      this.getPayPrice();
    },
    // 切换支付方式获取价格
    getPayPrice() {
      this.$http
        .orderGet_pay_price({ order_id: this.order_id, pay_id: this.payId })
        .then((res) => {
          console.log(res, "切换状态获取价格");
          // this.goPage()
          this.price = res.data.pay_price;
          this.pageUrl = res.data.url;
          this.yitianType = res.data.type
        })
        .catch((error) => {
          console.log(error);
          uni.$u.toast(error);
        });
    },
    // 支付
    subPay() {
      if (this.password == "") {
        return uni.$u.toast("请输入密码");
      }
      this.Niule_pay();
    },
    // 提交支付密码
    subPwd() {
      if (this.mobile == "") {
        if(this.email_or_phone == 2){
          return uni.$u.toast("请输入邮箱");
        } else {
          return uni.$u.toast("请输入手机号");
        }
      }
      if (this.smsCode == "") {
        return uni.$u.toast("请输入验证码");
      }
      if (this.password == "") {
        return uni.$u.toast("请输入密码");
      }
      if (this.password2 == "") {
        return uni.$u.toast("请再次输入密码");
      }
      this.setPwd();
    },
    // 提交支付
    async subFn() {
      let that = this;
      // 判断是否选中支付方式
      let flag = 0;
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].clickable == true) {
          flag = 1;
        }
      }
      // 已选择支付方式
      if (flag == 1) {
        uni.$u.toast("支付啦");
        // 牛勒支付
        if (this.payId == 5) {
          this.getPayPwd();
        } else if (this.payId == 2) {
          // 先调支付宝支付接口获取订单字符串
          await this.getAlipayOrder();
          // 支付宝支付
          await setTimeout(() => {
            uni.requestPayment({
              provider: "alipay", //固定值为"alipay"
              orderInfo: this.alipayOrderStr, //此处为服务器返回的订单信息字符串
              success: function (res) {
                var rawdata = JSON.parse(res.rawdata);
                console.log("支付成功", res);
                that.getOrderStatus();
              },
              fail: function (err) {
                console.log("支付失败:" + JSON.stringify(err));
              },
            });
          }, 1000);
        // paypal支付
        } else if(this.payId == 4){
          await this.getPaypalOrder()
          
        }
      } else {
        uni.$u.toast("请选择支付方式");
      }
    },
    // 查询订单状态
    getOrderStatus() {
      this.$http
        .orderGet_order_status({ order_id: this.order_id })
        .then((res) => {
          console.log(res, "查询支付状态");
          this.goPage();
        })
        .catch((error) => {
          console.log(error);
          uni.$u.toast(error);
        });
    },
    // 获取paypal订单
    getPaypalOrder(){
      this.$http
        .orderPaypal_pay({
          order_id: this.order_id,
        })
        .then((res) => {
          this.alipayOrderStr = res.data.res.order_info;
          console.log(res.data.res, "paypal订单字符串");
          // paypal支付
          setTimeout(() => {
            uni.requestPayment({
              provider: "paypal", //固定值为"alipay"
              orderInfo: this.alipayOrderStr, //此处为服务器返回的订单信息字符串
              _debug:1,
              success: function (res) {
                // var rawdata = JSON.parse(res.rawdata);
                console.log("支付成功", res);
                // that.getOrderStatus();
              },
              fail: function (err) {
                console.log("支付失败:" + JSON.stringify(err));
              },
            });
          }, 1000);
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    // 获取支付宝订单
    getAlipayOrder() {
      this.$http
        .orderAli_pay({
          order_id: this.order_id,
        })
        .then((res) => {
          this.alipayOrderStr = res.data.res;
          console.log(res.data.res, "支付宝订单字符串");
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    // 支付成功后跳转页面
    goPage() {
      // 如果是从订单列表也进入的   回退页面  其他的跳转
      if (this.from == "myDingdan" || this.from == "daohang") {
        uni.navigateBack({
          delta: 1,
        });
      } else if(this.from == "kecheng"){
        uni.redirectTo({
          url: `${this.pageUrl}?id=${this.id}&type=${this.type}`,
        });
      } else {
        console.log(this.pageUrl,'123123123')
        if(this.yitianType == 5){
          // 跳订单详情
          uni.redirectTo({
            url: '/pages/integral/indent',
          });
        } else if(this.yitianType == 2 || this.yitianType == 4){
          uni.redirectTo({
            url: `${this.pageUrl}?id=${this.id}`,
          });
        }
        else {
          // 后台配置页面跳转
          uni.redirectTo({
            url: `${this.pageUrl}&id=${this.id}`,
          });
        }
        
      }

      

      // 前端写死页面跳转
      // if (this.from == "wendaoshan") {
      //   uni.redirectTo({
      //     url: `/pages/detail/wenForm?id=${this.id}`,
      //   });
      //   console.log(this.detail);
      // } else if (this.from == "kecheng") {
      //   uni.redirectTo({
      //     url: `/pages/bigResult/myResult_it?id=${this.id}`,
      //   });
      // } else if (this.from == "myDingdan") {
      //   uni.navigateBack({
      //     delta: 1,
      //   });
      // }
    },
    // 支付接口
    Niule_pay() {
      this.$http
        .orderNiule_pay({
          pay_password: this.password,
          order_id: this.order_id,
        })
        .then((res) => {
          this.showPwd = false;
          this.password = "";
          uni.$u.toast(res.message);
          setTimeout(() => {
            this.goPage();
          }, 1000);
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    // 设置支付密码接口
    setPwd() {
      this.$http
        .orderSet_pay_password({
          password: this.password,
          password2: this.password2,
          mobile: this.mobile,
          smsCode: this.smsCode,
          email_or_phone:this.email_or_phone
        })
        .then((res) => {
          console.log(res, "设置支付密码");
          this.password = "";
          this.password2 = "";
          this.mobile = "";
          this.smsCode = "";
          uni.$u.toast(res.message);
          this.show = false;
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    // 是否设置支付密码
    getPayPwd() {
      this.$http
        .orderPay_password({})
        .then((res) => {
          // this.list = res.data.list;
          if (res.data.status == 1) {
            // 已设置
            this.showPwd = true;
            this.email_or_phone = res.data.email_or_phone
          } else {
            // 未设置
            this.show = true;
          }
          this.email_or_phone = res.data.email_or_phone
          console.log(res, "是否设置支付密码");
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    // 获取支付方式列表
    getPayList() {
      this.$http
        .appversionGet_pay_type({})
        .then((res) => {
          this.list = res.data.list;
          for (let i = 0; i < this.list.length; i++) {
            this.list[i].clickable = false;
          }
          // this.xiaoyaoList = data;
          console.log(res, "支付方式");
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
  },
};
</script>
    
<style scoped lang="scss">
.content {
  box-sizing: border-box;
}
.head {
  width: 100%;
  padding: 18rpx 30rpx 47rpx;
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  z-index: 99;
  background: #fff;

  .head_left {
    position: absolute;
    left: 30rpx;
  }

  .head_right {
    position: absolute;
    right: 30rpx;
    display: flex;
  }

  .text {
    font-size: 36rpx;
    font-family: PingFang SC-Bold, PingFang SC;
    font-weight: 400;
    color: #444444;
  }
}
.box {
  padding: 30rpx;
  box-sizing: border-box;
  .box_top {
    margin-top: 70rpx;
    .box_top_title {
      font-size: 28rpx;
      color: #888888;
      text-align: center;
    }
    .box_top_price {
      margin-top: 16rpx;
      text-align: center;
      .box_top_price_unit {
        font-size: 40rpx;
        display: inline-block;
      }
      .box_top_price_num {
        font-size: 72rpx;
        display: inline-block;
      }
    }
  }
  .box_content {
    margin-top: 120rpx;
    .box_content_title {
      font-size: 32rpx;
      color: #444444;
    }
    .box_content_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 43rpx;
      .box_content_item_left {
        display: flex;
        align-items: center;
        .box_content_item_left_img {
          width: 58rpx;
          height: 58rpx;
        }
        .box_content_item_left_title {
          margin-left: 16rpx;
          font-size: 30rpx;
          color: #444444;
        }
      }
      .box_content_item_right {
        width: 34rpx;
        height: 34rpx;
        image {
          width: 34rpx;
          height: 34rpx;
        }
      }
    }
  }
}

.bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  margin-bottom: 80rpx;
  .bottom_btn {
    width: 630rpx;
    height: 96rpx;
    background: linear-gradient(360deg, #50b674 0%, #aeddbd 100%);
    border-radius: 48rpx;
    text-align: center;
    line-height: 96rpx;
    font-size: 30rpx;
    color: #ffffff;
    margin: 0 auto;
  }
}

.niuPop {
  padding: 40rpx;
  box-sizing: border-box;
  .niuPop_title {
    text-align: center;
    font-size: 40rpx;
  }
  /deep/.inputPassword {
    // width: 630rpx;
    height: 96rpx;
    background-color: #f4f4f4;
    margin-top: 40rpx;
    position: relative;

    .u-input__content {
      padding: 0 50rpx;
    }
    .codeTip {
      position: absolute;
      right: 50rpx;
      bottom: 30rpx;
      font-size: 30rpx;
      font-weight: 400;
      color: #55b877;
    }
  }
  .confirm_btn {
    // width: 630rpx;
    height: 96rpx;
    margin-top: 54rpx;
    background: linear-gradient(360deg, #50b674 0%, #aeddbd 100%);
    border-radius: 48rpx 48rpx 48rpx 48rpx;
    text-align: center;
    line-height: 96rpx;
    color: white;
  }
}
</style>